#!/usr/bin/perl -w

use strict;


# Check arguments
if (@ARGV == 0) {
    die "Need file name as argument\nUsage: $0 file\n";
}


# Read the file
my $filename = $ARGV[0];
open FILE, $filename or die "Couldn't open file '$filename': $!\n";
my @lines = <FILE>;
close FILE or warn "Problems closing file '$filename': $!\n";

my $line = $lines[0];
chomp $line;
$line =~ s/^\s+|\s+$//g;

if (length($line) != 41) {
    die "Unexpected length of line. Expected a length of 41.\n";
}


my @squares;


# Parse the wdp format

my $i = 0;
my $square_nbr = 0;
while ($i < 40) {
    my $char;
    for (my $j = 0; $j < 4; $j++) {
        $char = substr $line, $i, 1;
        if ($char =~ /^[bBwW\.]$/) {
            $char =~ tr/\./-/;
            $squares[$square_nbr] = $char;
        } else {
            die "Unexpected character '$char'. Expected one of",
                " ., b, B, w, or W\n";
        }
        $square_nbr++;
        $i++;
    }
    $char = substr $line, $i, 1;
    if ($char ne ' ') {
        die "Unexpected character '$char'. Expected ' '.\n";
    }
    $i++;
}

my $turn = substr $line, 40, 1;
$turn = lc $turn;
if ($turn !~ /^[bw]$/) {
    die "Unexpected character '$turn'. Expected one of b, B, w, or W\n";
}
$squares[32] = $turn;


# Print out in cwb format
for (my $row = 0; $row < 8; $row++) {
    my $odd_row = $row & 1;
    if (not $odd_row) {
        print '  ';
    }

    my $from = $row * 4;
    my $to = $from + 3;
    printf "%s   %s   %s   %s", @squares[$from .. $to];

    if ($odd_row) {
        print '  ';
    }
    print "\n";
}
print $squares[32], "\n";
